package memberrewards.service;

import hackathon1212.ServletPojoAdapter;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import memberrewards.delegate.RewardsDelegate;
import memberrewards.dtos.AccountDetailDTO;
import memberrewards.dtos.CatalogItemDTO;
import static memberrewards.helpers.Constants.BLANK;

public class SearchCatalog extends ServletPojoAdapter {
	private static final long serialVersionUID = 8166717310334174053L;

	protected Map<String,Object> getBusinessMethod(Map<String, String[]> params){
		//Query Params
		final String pan =params.get("pan")!=null? params.get("pan")[0]:null;
		final String searchKey = params.get("searchkey") != null ? params.get("searchkey")[0] : null;
		
		//Default response
		final Map<String,Object> ret = new HashMap<String, Object>();
		ret.put("status", "Card Not Found");
		ret.put("searchresults", null);
		//gest the account details
		final AccountDetailDTO accountDetail = RewardsDelegate.getAccountDetail(pan);		
		//Check card is valid
		if (accountDetail!=null) {	
			List<CatalogItemDTO> items;
			if (searchKey != null && (!BLANK.equals(searchKey))) {
				//Perform the search
				items = RewardsDelegate.getSearchResult(accountDetail.getTier(), searchKey);			
			}else{
				//get everything back
				items = RewardsDelegate.getEligibleCatalogList(accountDetail.getTier());
			}
			if (items != null && !items.isEmpty()) {
				final List<Map<String,String>> searchResults = new LinkedList<Map<String,String>>();
				//This may require Some Extra Work,No need to Expose Internals to users.Pass only the required information
				populateSearchResults(items,searchResults);
				//found something
				ret.put("searchresults", searchResults);
				ret.put("status", "Success");
			}else{
				ret.put("status", "No Catalog Items Found");;
			}
		}
		return ret;
	}
	
	private final void  populateSearchResults(final List<CatalogItemDTO> items,final List<Map<String,String>> searchResults){
		for (CatalogItemDTO catalogItem : items) {
			try {
				final Map<String, String> searchResult = new LinkedHashMap<String, String>();
				searchResult.put("itemid", catalogItem.getItemid());
				searchResult.put("name", catalogItem.getName());
				searchResult.put("make", catalogItem.getMake());
				searchResult.put("description", catalogItem.getDescription());
				searchResult.put("pointCost",
						String.valueOf(catalogItem.getPointCost()));
				searchResults.add(searchResult);
			} catch (RuntimeException rtExc) {
				//NOOP
			}
		}	
	}
}
